<template>
  <div>
    <ContentHeader title="课程分类管理">
      <template #title>
        <el-button type="primary" size="small" @click="handleCreate(0)">
          <el-icon><Plus /></el-icon> 添加主分类
        </el-button>
      </template>
    </ContentHeader>
    <ContentBody v-loading="store.loading">
      <el-table :data="store.categories" 
        :stripe="true" 
        :highlight-current-row="true"
        row-key="id"
      >
        <el-table-column property="id" width="80" />
        <el-table-column property="title" label="名称" />
        <el-table-column label="操作" width="350">
          <template #default="scope">
            <el-button plain v-if="scope.row.parentId == 0" @click="handleCreate(scope.row.id)">
              <el-icon size="small"><CirclePlus /></el-icon> 添加子分类
            </el-button>
            <el-button plain @click="handleUpdate(scope.row.id)">
              <el-icon size="small"><Edit /></el-icon> 修改
            </el-button>
            <el-button plain :disabled="scope.row.children && scope.row.children.length > 0" @click="handleDelete(scope.row)">
              <el-icon size="small"><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </ContentBody>
    <RouterView />
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCategotryStore } from '@/stores/category'
import { Edit, Delete, CirclePlus, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import type { CategoryItem } from '@/config/types';

const store = useCategotryStore()
const router = useRouter()
const handleCreate = (pid: number) => router.push({name: 'course_category_create', query:{ parentId: pid }})
const handleUpdate = (id: number) => router.push({name: 'course_category_update', params: {id: id}})
const handleDelete = (item: CategoryItem) => {
  ElMessageBox.confirm('确定要删除'+ item.title +'吗', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async() => {
    const result = await store.removeCategory(item.id)
    if (result) {
      ElMessage.success('删除成功')
      store.loadCategories()
    }
  })
}

onMounted(() => store.loadCategories())
</script>